define(["knockout", "durandal/system", "models/coin-winner/Member","jquery","ps"], function(
  ko,
  system,
  Member,
  $,
  ps
) {
  var state = {
    members: ko.observableArray([]),
    memberCount: ko.observable(100),
    isOver: ko.observable(false),
    youWish: ko.observable(1)
  };
  var moduleRootDom=null;

  function handleChangeMemberCount() {
    var count = parseInt(state.memberCount.peek());
    var newMembers=[];
    for (var index = 1; index <= count; index++) {
      var member = new Member(index, "玩家 " + index, 0);
      newMembers.push(member);
    }
    state.members(newMembers);
    state.isOver(false);
    $(".list",moduleRootDom).perfectScrollbar("update");
  }

  function isFront() {
    var ran = Math.ceil(Math.random() * 10) + 1;
    //如果随机数在1-5（包含5），就认为是正面，在6-10是反面
    return ran < 6;
  }

  function handleThrowCoin() {
    var members = state.members();
    var isOver = state.isOver();
    var youWish = state.youWish();

    if (isOver) {
      alert("游戏结束，请点击变更人数开始新的一轮");
      return;
    }
    var newMembers = [];
    for (var index = 0; index < members.length; index++) {
      var member = members[index];
      //如果是正面才进入下一轮
      if (isFront()) {
        var newMember = member.clone();
        newMember.winCount(member.winCount() + 1);
        newMembers.push(newMember);
      }
    }

    if (newMembers.length === 0) {
      var exist = false;

      for (var index = 0; index < members.length; index++) {
        var m = members[index];
        if (m.id() === parseInt(youWish)) {
          exist = true;
          break;
        }
      }

      if (exist) {
        alert("您很幸运到了最后");
      } else {
        alert("您被淘汰了呢");
      }

      alert("游戏结束，剩下的都是百年难遇的幸运儿");
      state.isOver(true);
    } else {
      state.members(newMembers);
    }
  }

  var exports = {
    activate: function() {
      system.log("Coin Winner [default] : activate");
    },
    binding: function() {
      system.log("Coin Winner [default] : binding");
    },
    bindingComplete: function() {
      system.log("Coin Winner [default] : bindingComplete");
    },
    attached: function(view, parent) {
      moduleRootDom=view;
      system.log("Coin Winner [default] : attached");
      this.state.memberCount(100);
      this.handleChangeMemberCount();
      $(".list",moduleRootDom).perfectScrollbar();
    },
    compositionComplete: function() {
      system.log("Coin Winner [default] : compositionComplete");
    },
    detached: function() {
      system.log("Coin Winner [default] : detached");
    },
    state: state,
    handleChangeMemberCount: handleChangeMemberCount,
    handleThrowCoin: handleThrowCoin
  };

  return exports;
});
